package leetcode.list;

import utils.node.ListNode;

/**
 * DESCRIPTION: https://leetcode-cn.com/problems/linked-list-cycle/
 * 给你一个链表的头节点 head ，判断链表中是否有环。
 * 提示：快慢指针(慢指针一次循环走1步，快指针一次循环走2步)
 * 如果链表中有某个节点，可以通过连续跟踪 next 指针再次到达，则链表中存在环。
 *
 * Author: ammar
 * Date:   2021/12/10
 * Time:   下午12:04
 */
public class _141_环形链表_判断链表是否有环 {

    public static void main(String[] args) {
        ListNode headCircle = Tools.generCircleList(new Integer[]{1, 2, 3, 4, 5}, new Integer[]{2,3,4});
        ListNode head = Tools.generList(new Integer[]{1, 2, 3, 4, 5});
        System.out.println(hasCycle(headCircle));
        System.out.println(hasCycle(head));
    }

    public static boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) return true;
        }
        return false;
    }
}
